import '@babel/polyfill';

// Vue
import Vue from 'vue';
import App from './App';

// 配置
import Setting from './setting';

// 混合
import mixinApp from '@/mixins/app';

// 插件
import plugins from '@/plugins';

// store
import store from '@/store/index';
// directive
import directive from './directive/preventReClick';

// iView 和 iView Pro
// import ViewUI from 'view-design';
import '../src/plugins/iview';
import iViewPro from '@/libs/iview-pro/iview-pro.min.js';

import '../src/plugins/element';
import 'element-ui/lib/theme-chalk/index.css';

// umy-ui
import '../src/plugins/umy';
import 'umy-ui/lib/theme-chalk/index.css';

import plTable from 'pl-table';
import 'pl-table/themes/index.css';

// Vxe-table
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'

import VXETablePluginElement from 'vxe-table-plugin-element'
// import 'vxe-table-plugin-element/dist/style.css'

// 菜单和路由
import router from './router';
import menuHeader from '@/menu/header';
import menuSider from '@/menu/sider';
import {
  frameInRoutes
} from '@/router/routes';

// 图片预览
import Viewer from 'v-viewer'
import 'viewerjs/dist/viewer.css'

// util 方法
import util from '@/libs/util';

// 多语言
import i18n from '@/i18n';

// 方法
import {
  getHeaderName,
  getMenuSider,
  getSiderSubmenu
} from '@/libs/system';

// 内置组件
import iLink from '@/components/link';

// 使用样式，修改主题可以在 styles 目录下创建新的主题包并修改 iView 默认的 less 变量
// 参考 https://www.iviewui.com/docs/guide/theme
import './styles/index.less';
import './libs/iview-pro/iview-pro.css';

import VideoPlayer from 'vue-video-player'

/* md5加密 */
import md5 from 'js-md5'
/* lodash */
import _ from 'lodash';

import '@/assets/less/format.less'

// 引入echarts
import echarts from '../src/plugins/echarts';
// 挂载到vue实例中
Vue.prototype.$echarts = echarts

window.videojs = VideoPlayer.videojs
router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  if (isChunkLoadFailed) {
    window.location.reload();
  } else {
    console.log(error)
  }
})
if (window) window.$t = (key, value) => i18n.t(key, value);

Vue.config.productionTip = false
Vue.config.devtools = false

Vue.use(plugins);
Vue.use(plTable);
Vue.use(VXETable);
VXETable.use(VXETablePluginElement)
Vue.use(iViewPro);
Vue.prototype.$ELEMENT = {
  size: 'small',
  zIndex: 3000
};
Vue.component('i-link', iLink);
require('video.js/dist/video-js.css')
require('vue-video-player/src/custom-theme.css')
require('video.js/dist/lang/zh-CN.js')
Vue.use(VideoPlayer)
Vue.use(directive)
// 图片预览
Vue.use(Viewer)
Viewer.setDefaults({
  Options: {
    'inline': true,
    'button': true,
    'navbar': true,
    'title': true,
    'toolbar': true,
    'tooltip': true,
    'movable': true,
    'zoomable': true,
    'rotatable': true,
    'scalable': true,
    'transition': true,
    'fullscreen': true,
    'keyboard': true,
    'url': 'data-source'
  }
})

// 注册全局过滤器：价格保留2位小数
Vue.filter('formatPrice', function (value = 0) {
  return Number(value).toFixed(2)
})
Vue.mixin({
  data () {
    return {
      imgBaseURL: Setting.imgBaseURL,
      imgBaseURL2: Setting.imgBaseURL2,
      videoBaseURL: Setting.videoBaseURL,
      IMURL: Setting.imURL,
      imgURL: Setting.imgURL,
      uploadBaseURL: Setting.uploadBaseURL,
      uploadMethord: Setting.uploadMethord,
      exportBaseURL: Setting.exportBaseURL,
      Spin: false,
      accountUuid: '',
      IMAGEURL: Setting.IMAGEURL,
      XOSSPROCE: Setting.XOSSPROCE,
      supplierExportConfig: {
        supplier: false, // 供应商管理模块
        returnViste: false, // 回访考察管理
        dataStatistics: false, // 数据统计查询
        supervision: true, // 核查管理
        inner: false, // 内部管理
        contract: false, // 合同管理
        kpi: false, // 绩效管理
      }
    }
  },
  created () {
    this.accountUuid = this.$store ? this.$store.state.admin.user.info.uuid : '';
  },
  methods: {
    // 时间转换
    formateDate (datetime) {
      var d = new Date(datetime);
      let year = d.getFullYear() >= 10 ? d.getFullYear() : '0' + d.getFullYear();
      let mouth = (d.getMonth() + 1) >= 10 ? (d.getMonth() + 1) : '0' + (d.getMonth() + 1);
      let day = d.getDate() >= 10 ? d.getDate() : '0' + d.getDate();
      return year + '-' + mouth + '-' + day;
    }
  }
});

Vue.prototype.$md5 = md5; // 全局引用md5
Vue.prototype._ = _;

new Vue({
  mixins: [mixinApp],
  router,
  store,
  i18n,
  render: h => h(App),
  created () {
    // 处理路由 得到每一级的路由设置
    this.$store.commit('admin/page/init', frameInRoutes);
    // 设置顶栏菜单
    this.$store.commit('admin/menu/setHeader', menuHeader);
    // 加载用户登录的数据
    this.$store.dispatch('admin/account/load');
    // 初始化全屏监听
    this.$store.dispatch('admin/layout/listenFullscreen')
  },
  watch: {
    // 监听路由 控制侧边栏显示 标记当前顶栏菜单（如需要）
    '$route' (to, from) {
      const path = to.path;
      let menuSiderList = [];
      if (!Setting.dynamicSiderMenu) {
        menuSiderList = menuSider;
        const headerName = getHeaderName(path, menuSiderList);
        // 在 404 时，是没有 headerName 的
        if (headerName !== null) {
          this.$store.commit('admin/menu/setHeaderName', headerName);

          const filterMenuSider = getMenuSider(menuSiderList, headerName);
          this.$store.commit('admin/menu/setSider', filterMenuSider);
          // 进入内页时，左侧高亮列表页 start
          let copyPath = path.substr(1);
          let pathArr = copyPath.split('/');
          let lastPath = pathArr[pathArr.length - 1];
          /**
           * Edit:编辑页，View：详情页，Add:新增，Audit：审核，NewEdit：新增/编辑
           */
          if (lastPath.indexOf('Edit') > -1) {
            lastPath = lastPath.replace('Edit', 'List');
          } else if (lastPath.indexOf('View') > -1) {
            lastPath = lastPath.replace('View', 'List');
          } else if (lastPath.indexOf('Add') > -1) {
            lastPath = lastPath.replace('Add', 'List');
          } else if (lastPath.indexOf('Audit') > -1) {
            lastPath = lastPath.replace('Audit', 'List');
          } else if (lastPath.indexOf('NewEdit') > -1) {
            lastPath = lastPath.replace('NewEdit', 'List');
          }
          pathArr[pathArr.length - 1] = lastPath;
          let newPath = '/' + pathArr.join('/');
          // 进入内页是，左侧高亮列表页 end
          this.$store.commit('admin/menu/setActivePath', newPath);

          const openNames = getSiderSubmenu(path, menuSiderList);
          this.$store.commit('admin/menu/setOpenNames', openNames);
        }
      } else {
        menuSiderList = JSON.parse(util.Pub.getStorageSync('userMenuList')) ? JSON.parse(util.Pub.getStorageSync('userMenuList')) : []
        let modulesP = path.split('/')[1];
        for (let o = 0; o < menuSiderList.length; o++) {
          let oMenu = menuSiderList[o];
          let openNames = [];
          if (oMenu.path.split('/')[1] === modulesP) {
            openNames = [oMenu.path]
          }
          if (oMenu.children && oMenu.children.length > 0) {
            let sMenuList = oMenu.children;
            for (let s = 0; s < sMenuList.length; s++) {
              let sMenu = sMenuList[s];
              if (sMenu.path.split('/').length > 2) {
                if (sMenu.path.split('/')[2] === path.split('/')[2]) {
                  openNames = [oMenu.path, sMenu.path]
                }
              } else {
                if (sMenu.path.split('/')[1] === path.split('/')[1]) {
                  openNames = [oMenu.path, sMenu.path]
                }
              }
              if (sMenu.children && sMenu.children.length > 0) {
                let tMenuList = sMenu.children;
                for (let t = 0; t < tMenuList.length; t++) {
                  let tMenu = tMenuList[t];
                  if (sMenu.path.split('/')[3] === path.split('/')[3]) {
                    openNames = [
                      oMenu.path,
                      sMenu.path,
                      tMenu.path
                    ];
                    break;
                  }
                }
              }
            }
          }
          this.$store.commit('admin/menu/setOpenNames', openNames);
          if (oMenu.path.split('/')[1] === modulesP) {
            break;
          }
        }
        if (menuSiderList && menuSiderList.length > 0) {
          this.$store.commit('admin/menu/setHeaderName', 'home');
          this.$store.commit('admin/menu/setSider', menuSiderList);
          this.$store.commit('admin/menu/setActivePath', path);
        }
      }
      this.appRouteChange(to, from);
    }
  }
}).$mount('#app');
